package com.njrsrc.common.utils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.ref.SoftReference;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.njrsrc.R;
import com.njrsrc.common.url.FileDirProvider;

/**
 * 
 * @author jianwen.zhu
 * 
 */
public class Helpers {
	/** 安装包没有安装 */
	public static int PACKAGE_NOT_INSTALL = -11;

	/**
	 * 创建应用文件夹
	 * 
	 * @return
	 * @throws IOException
	 */
	public static boolean createFS() throws Exception {
		File file = Environment.getExternalStorageDirectory();
		if (!file.canWrite()) {
			return false;
		}
		ArrayList<File> dirs = new ArrayList<File>();
		Field[] fields = FileDirProvider.class.getDeclaredFields();
		for (Field f : fields) {
			dirs.add(new File(f.get(null).toString()));
		}
		for (File dir : dirs) {
			if (!dir.exists()) {
				dir.mkdirs();
			}
		}
		return true;
	}

	/**
	 * 检测网络状态
	 * 
	 * @param context
	 * @return
	 */
	public static State checkNetworkInfo(Context context) {
		ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

		// mobile 3G Data Network
		State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
		// wifi
		State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();

		// 如果3G网络和wifi网络都未连接，且不是处于正在连接状态 则进入Network Setting界面 由用户配置网络连接
		if (mobile == State.CONNECTED)
			return mobile;
		if (wifi == State.CONNECTED)
			return wifi;
		return null;

	}

	/**
	 * 显示对话框
	 * 
	 * @param context
	 * @param title
	 *            Dialog title
	 * @param message
	 *            Dialog message
	 * @return
	 */
	public static AlertDialog.Builder showDialog(Context context, String title, String message, int[] buttonTexts,
			OnClickListener[] listeners) {
		AlertDialog.Builder dialog = new AlertDialog.Builder(context);
		dialog.setTitle(title);
		dialog.setMessage(message);
		if (buttonTexts.length == 1) {
			dialog.setNeutralButton(buttonTexts[0], listeners[0]);
		} else if (buttonTexts.length == 2) {
			dialog.setPositiveButton(buttonTexts[0], listeners[0]);
			dialog.setNegativeButton(buttonTexts[1], listeners[1]);
		} else if (buttonTexts.length == 3) {
			dialog.setPositiveButton(buttonTexts[0], listeners[0]);
			dialog.setNeutralButton(buttonTexts[1], listeners[1]);
			dialog.setNegativeButton(buttonTexts[2], listeners[2]);
		}
		dialog.show();
		return dialog;
	}

	public static AlertDialog.Builder showDialog(Context context, int title, int message, int[] buttonTexts,
			OnClickListener[] listeners) {
		AlertDialog.Builder dialog = new AlertDialog.Builder(context);
		dialog.setTitle(title);
		dialog.setMessage(message);
		if (buttonTexts.length == 1) {
			dialog.setNeutralButton(buttonTexts[0], listeners[0]);
		} else if (buttonTexts.length == 2) {
			dialog.setPositiveButton(buttonTexts[0], listeners[0]);
			dialog.setNegativeButton(buttonTexts[1], listeners[1]);
		} else if (buttonTexts.length == 3) {
			dialog.setPositiveButton(buttonTexts[0], listeners[0]);
			dialog.setNeutralButton(buttonTexts[1], listeners[1]);
			dialog.setNegativeButton(buttonTexts[2], listeners[2]);
		}
		dialog.show();
		return dialog;
	}

	/**
	 * show progress dialog
	 * 
	 * @param context
	 * @param title
	 *            Dialog title
	 * @param message
	 *            Dialog message
	 * @return
	 */
	public static ProgressDialog showProgressDialog(Context context, int title, int message) {
		ProgressDialog dialog = new ProgressDialog(context);
		dialog.setTitle(title);
		dialog.setMessage(context.getResources().getString(message));
		dialog.setIndeterminate(true);
		dialog.setCancelable(true);
		dialog.show();
		return dialog;
	}

	public static ProgressDialog showProgressDialog(Context context, int message) {
		ProgressDialog dialog = new ProgressDialog(context);
		dialog.setMessage(context.getResources().getString(message));
		dialog.setIndeterminate(true);
		dialog.setCancelable(true);
		dialog.show();
		return dialog;
	}

	/**
	 * 关闭progress dialog
	 * 
	 * @param progressDialog
	 */
	public static void closeProgressDialog(Dialog progressDialog) {
		if (progressDialog != null && progressDialog.isShowing()) {
			progressDialog.cancel();
		}
	}

	private static final String ACTION_INSTALL_SHORTCUT = "com.android.launcher.action.INSTALL_SHORTCUT";

	/*
	 * 是否可以有多个快捷方式的副本
	 */
	static final String EXTRA_SHORTCUT_DUPLICATE = "duplicate";

	/**
	 * install shortcut on desktop
	 * 
	 * @param context
	 */
	public static void installShortCut(final Context context) {
		Intent shortcutIntent = new Intent(ACTION_INSTALL_SHORTCUT);
		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, context.getResources().getString(R.string.app_name));
		shortcutIntent.putExtra(EXTRA_SHORTCUT_DUPLICATE, false);
		Intent intent2 = new Intent(Intent.ACTION_MAIN);
		intent2.addCategory(Intent.CATEGORY_LAUNCHER);

		intent2.setComponent(new ComponentName(context.getPackageName(), context.getPackageName()
				+ ".TitlesDefaultActivity"));

		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent2);
		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
				Intent.ShortcutIconResource.fromContext(context, R.drawable.launch_icon));
		context.sendBroadcast(shortcutIntent);
	}

	/**
	 * create new file
	 * 
	 * @param f
	 * @throws Exception
	 */
	public static void createNewFile(File f) throws Exception {
		if (!f.getParentFile().exists()) {
			f.getParentFile().mkdirs();
		}
		if (!f.exists()) {
			f.createNewFile();
		}
	}

	/**
	 * 删除指定目录下的文件
	 * 
	 * @param dir
	 */
	public static void deleteFile(File dir) {
		if (dir.exists() && dir.isDirectory()) {
			File[] childs = dir.listFiles();
			for (File f : childs) {
				if (f.exists() && f.isDirectory()) {
					continue;
				} else if (f.exists() && f.isFile()) {
					f.delete();
				}
			}
			dir.delete();
		} else if (dir.exists() && dir.isFile()) {
			dir.delete();
		}
	}

	/**
	 * 递归删除目录
	 * 
	 * @param dir
	 */
	public static void deleteDir(File dir) {
		if (dir.exists() && dir.isDirectory()) {
			File[] childs = dir.listFiles();
			for (File f : childs) {
				if (f.exists() && f.isDirectory()) {
					deleteDir(f);
				} else if (f.exists()) {
					f.delete();
				}
			}
			dir.delete();
		} else if (dir.exists()) {
			dir.delete();
		}
	}

	/**
	 * 根据大小缩放图片
	 * 
	 * @param in
	 * @param targetWidth
	 * @param targetHeight
	 * @return
	 */
	public static Bitmap scaleBitmap(String filePath, int targetWidth, int targetHeight) {
		// get sampleBitmap
		Options opts = new Options();
		opts.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filePath, opts);

		int scaleWidth = opts.outWidth / targetWidth;
		int scaleHeight = opts.outHeight / targetHeight;
		int scale = scaleWidth < scaleHeight ? scaleWidth : scaleHeight;
		if (scale < 1) {
			scale = 1;
		}
		opts.inJustDecodeBounds = false;
		opts.inSampleSize = scale;
		Bitmap sampleBitmap = BitmapFactory.decodeFile(filePath, opts);

		if (opts.outWidth == -1 || opts.outHeight == -1) {
			return null;
		}
		// get scalebitmap
		float fScaleWidth = targetWidth / ((float) opts.outWidth);
		float fScaleHeight = targetHeight / ((float) opts.outHeight);
		float fScale = fScaleWidth > fScaleHeight ? fScaleWidth : fScaleHeight;
		if (fScale > 1)
			fScale = 1;
		Matrix matrix = new Matrix();
		matrix.postScale(fScale, fScale);
		Bitmap scaleBitmap = Bitmap.createBitmap(sampleBitmap, 0, 0, opts.outWidth, opts.outHeight, matrix, true);

		// get targetBitmap
		int bitmapX = (scaleBitmap.getWidth() - targetWidth) / 2;
		bitmapX = bitmapX > 0 ? bitmapX : 0;
		int bitmapY = (scaleBitmap.getHeight() - targetHeight) / 2;
		bitmapY = bitmapY > 0 ? bitmapY : 0;
		targetWidth = targetWidth < (scaleBitmap.getWidth()) ? targetWidth : (scaleBitmap.getWidth());
		targetHeight = targetHeight < (scaleBitmap.getHeight()) ? targetHeight : (scaleBitmap.getHeight());
		Bitmap targetBitmap = Bitmap.createBitmap(scaleBitmap, bitmapX, bitmapY, targetWidth, targetHeight);

		// scaleBitmap.recycle();
		// sampleBitmap.recycle();
		return targetBitmap;
	}
	
	/**
	 * 根据大小缩放图片,并旋转角度
	 * 
	 * @param in
	 * @param targetWidth
	 * @param targetHeight
	 * @return
	 */
	public static Bitmap scaleBitmap(String filePath, int targetWidth, int targetHeight,int angle) {
		// get sampleBitmap
		Options opts = new Options();
		opts.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filePath, opts);

		int scaleWidth = opts.outWidth / targetWidth;
		int scaleHeight = opts.outHeight / targetHeight;
		int scale = scaleWidth < scaleHeight ? scaleWidth : scaleHeight;
		if (scale < 1) {
			scale = 1;
		}
		opts.inJustDecodeBounds = false;
		opts.inSampleSize = scale;
		Bitmap sampleBitmap = BitmapFactory.decodeFile(filePath, opts);

		if (opts.outWidth == -1 || opts.outHeight == -1) {
			return null;
		}
		// get scalebitmap
		float fScaleWidth = targetWidth / ((float) opts.outWidth);
		float fScaleHeight = targetHeight / ((float) opts.outHeight);
		float fScale = fScaleWidth > fScaleHeight ? fScaleWidth : fScaleHeight;
		if (fScale > 1)
			fScale = 1;
		Matrix matrix = new Matrix();
		if(angle != 0)
		{
			matrix.setRotate(angle);
		}
		matrix.postScale(fScale, fScale);
		Bitmap scaleBitmap = Bitmap.createBitmap(sampleBitmap, 0, 0, opts.outWidth, opts.outHeight, matrix, true);

		// get targetBitmap
		int bitmapX = (scaleBitmap.getWidth() - targetWidth) / 2;
		bitmapX = bitmapX > 0 ? bitmapX : 0;
		int bitmapY = (scaleBitmap.getHeight() - targetHeight) / 2;
		bitmapY = bitmapY > 0 ? bitmapY : 0;
		targetWidth = targetWidth < (scaleBitmap.getWidth()) ? targetWidth : (scaleBitmap.getWidth());
		targetHeight = targetHeight < (scaleBitmap.getHeight()) ? targetHeight : (scaleBitmap.getHeight());
		Bitmap targetBitmap = Bitmap.createBitmap(scaleBitmap, bitmapX, bitmapY, targetWidth, targetHeight);

		// scaleBitmap.recycle();
		// sampleBitmap.recycle();
		return targetBitmap;
	}


	public static byte[] readInstream(InputStream inputStream) throws IOException {
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int length = -1;
		while ((length = inputStream.read(buffer)) != -1) {
			byteArrayOutputStream.write(buffer, 0, length);
		}
		byteArrayOutputStream.close();
		inputStream.close();
		Log.i("test", byteArrayOutputStream.toByteArray().toString());
		return byteArrayOutputStream.toByteArray();
	}

	public static boolean isFileExists(String path, String appSize) {
		File file = new File(path);

		if (isFileExists(file)) {
			long fileSize = getFileSize(file);
			DecimalFormat df = new DecimalFormat("##0.00");

			StringBuffer sb = new StringBuffer();
			sb.append(df.format((double) fileSize / 1048576));

			return sb.toString().equals(appSize);
		}
		return false;
	}

	public static boolean isFileExists(File file) {
		return file.exists();
	}

	/**
	 * 获取文件大小
	 * 
	 * @param f
	 */
	public static long getFileSize(File f) {
		long s = 0;
		FileInputStream fis = null;
		try {
			if (f.exists() && f.isFile()) {
				fis = new FileInputStream(f);
				s = fis.available();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return s;
	}

	public static int isPkgInstalled(Context context, String pkgName) {
		PackageInfo packageInfo;
		try {
			packageInfo = context.getPackageManager().getPackageInfo(pkgName, 0);
		} catch (NameNotFoundException e) {
			packageInfo = null;
			e.printStackTrace();
		}

		return packageInfo == null ? PACKAGE_NOT_INSTALL : packageInfo.versionCode;
	}

	public static String getFormatString(String dateStr, Context context) {
		long currentTimeMillions = System.currentTimeMillis();
		long differ = currentTimeMillions - getTimeMillions(dateStr);
		if (differ <= 59 * 1000) {
			return context.getResources().getString(R.string.recently);
		} else if (differ >= 60 * 1000 && differ <= 59 * 60 * 1000) {
			return (differ / (60 * 1000)) + context.getResources().getString(R.string.minutesAgo);
		} else if (differ >= 60 * 60 * 1000 && differ < 23 * 60 * 60 * 1000) {
			return (differ / (60 * 60 * 1000)) + context.getResources().getString(R.string.hoursAgo);
		}

		return dateStr;

	}

	public static long getTimeMillions(String dateStr) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = null;
		try {
			date = format.parse(dateStr);
			return date.getTime();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return 0;
	}
	
	public static long getTimeMillionsByString(String dateStr) {
	    SimpleDateFormat format = null;
	    if (dateStr.length() == 10) {
            // 10月、11、12
	        format = new SimpleDateFormat("yyyy-MM-dd");
        } else {
            format = new SimpleDateFormat("yyyy-M-dd");
        }
        Date date = null;
        try {
            date = format.parse(dateStr);
            return date.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

	public static String getStandardTimeStr(Context context, String dateStr) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date date = new Date(dateStr);

		Calendar current = Calendar.getInstance();
		int currentYear = current.get(Calendar.YEAR);
		int currentMonth = current.get(Calendar.MONTH);
		int currentDay = current.get(Calendar.DATE);

		Calendar itemCalendar = Calendar.getInstance();
		itemCalendar.setTime(date);
		int itemYear = itemCalendar.get(Calendar.YEAR);
		int itemMonth = itemCalendar.get(Calendar.MONTH);
		int itemDay = itemCalendar.get(Calendar.DATE);

		if (currentYear == itemYear && currentMonth == itemMonth) {
			if (currentDay == itemDay) {
				return context.getResources().getString(R.string.today);
			} else if ((currentDay - 1) == itemDay) {
				return context.getResources().getString(R.string.yesterday);
			} else if ((currentYear + 1) == itemDay) {
				return context.getResources().getString(R.string.tomorrow);
			}
		}

		return format.format(date);
	}
	
	public static boolean isFutureTime(String dateStr)
	{
		Date date = new Date(dateStr);

		Calendar current = Calendar.getInstance();
		int currentYear = current.get(Calendar.YEAR);
		int currentMonth = current.get(Calendar.MONTH);
		int currentDay = current.get(Calendar.DATE);

		Calendar itemCalendar = Calendar.getInstance();
		itemCalendar.setTime(date);
		int itemYear = itemCalendar.get(Calendar.YEAR);
		int itemMonth = itemCalendar.get(Calendar.MONTH);
		int itemDay = itemCalendar.get(Calendar.DATE);

		if(itemYear > currentYear)
		{
			return true;
		}else if(itemYear == currentYear)
		{
			if(itemMonth > currentMonth)
			{
				return true;
			}else if(itemMonth == currentMonth)
			{
				if(itemDay >= currentDay)
				{
					return true;
				}
			}
		}

		return false;
	}

	/**
	 * 返回 yyyy-MM-dd 格式 的当前的时间 * @return
	 */
	public static String getFixFormatDate() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date date = new Date();
		return format.format(date);
	}

	/**
	 * 返回 yyyy-MM-dd HH:mm:ss 格式 的当前的时间 * @return
	 */
	public static String getAccurateFixFormatDate() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		return format.format(date);
	}

	/**
	 * 返回 yyyy-MM-dd HH:mm 格式 的当前的时间 * @return
	 */
	public static String getDimFixFormatDate() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		Date date = new Date();
		return format.format(date);
	}

	public static long getTimeMillions(int hour, int minute) {
		Calendar c = Calendar.getInstance();
		c.set(Calendar.HOUR_OF_DAY, hour);
		c.set(Calendar.MINUTE, minute);
		long time = c.getTimeInMillis();
		return time;
	}

	public static long getNextTimeMillions(int hour, int minute) {
		Calendar c = Calendar.getInstance();
		long nowTime = c.getTimeInMillis();

		c.set(Calendar.HOUR_OF_DAY, hour);
		c.set(Calendar.MINUTE, minute);
		long time = c.getTimeInMillis();

		if (nowTime > time) {
			c.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH) + 1);
			time = c.getTimeInMillis();
		}
		return time;
	}

	/**
	 * 使用post的方式，提交表单，不包括文件上传
	 * 
	 * @param actionUrl
	 * @param params
	 * @param files
	 * @return
	 * @throws IOException
	 */
	// public static JSONObject postParams(String actionUrl, Map<String, String>
	// params) throws IOException {
	// String BOUNDARY = java.util.UUID.randomUUID().toString();
	// String PREFIX = "--", LINEND = "\r\n";
	// String MULTIPART_FROM_DATA = "multipart/form-data";
	// String CHARSET = "UTF-8";
	//
	// URL uri = new URL(actionUrl);
	// HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
	//
	// conn.setReadTimeout(10 * 1000);
	// conn.setDoInput(true);// 允许输入
	// conn.setDoOutput(true);// 允许输出
	// conn.setUseCaches(false);
	// conn.setRequestMethod("POST"); // Post方式
	// conn.setRequestProperty("connection", "keep-alive");
	// conn.setRequestProperty("Charsert", "UTF-8");
	//
	// conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA +
	// ";boundary=" + BOUNDARY);
	//
	// // 首先组拼文本类型的参数
	// StringBuilder sb = new StringBuilder();
	// for (Map.Entry<String, String> entry : params.entrySet()) {
	// sb.append(PREFIX);
	// sb.append(BOUNDARY);
	// sb.append(LINEND);
	// sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() +
	// "\"" + LINEND);
	// sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
	// sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
	// sb.append(LINEND);
	// sb.append(entry.getValue());
	// sb.append(LINEND);
	// }
	//
	// DataOutputStream outStream = new
	// DataOutputStream(conn.getOutputStream());
	// outStream.write(sb.toString().getBytes());
	//
	// // 请求结束标志
	// byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
	// outStream.write(end_data);
	// outStream.flush();
	// // 得到响应码
	// int res = conn.getResponseCode();
	// String msg = conn.getResponseMessage();
	//
	// outStream.close();
	// conn.disconnect();
	//
	// try {
	// if (res == HttpURLConnection.HTTP_OK) {
	// return new JSONObject(msg);
	// }
	// } catch (JSONException e) {
	// e.printStackTrace();
	// }
	//
	// return null;
	// }

	/**
	 * combina the url. usr the param list repleace the [#] in the url.
	 * 
	 * @param str
	 * @param params
	 * @return
	 * @exception RuntimeException
	 *                May throw the runtime exception while the method was done.
	 * @author MichaelHuang
	 */
	public static String combinaStr(String str, List<String> params) throws RuntimeException {
		try {
			String[] strs = str.split("[#]");
			String newStr = "";
			for (int i = 0; i < strs.length; i++) {
				String itemUrl = strs[i];
				newStr += itemUrl;
				if (i >= 0 && i < params.size())
					newStr += params.get(i);
			}
			// Logger.debug("do: " + newStr);
			System.out.println("测试地址newString：" + newStr);
			return newStr;
		} catch (Exception e) {
			throw new RuntimeException();
		}
	}

	public static JSONObject getJSONArrayByGet(String uri) {
		StringBuilder builder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(uri);

		try {
			HttpResponse response = client.execute(get);

			BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			for (String s = reader.readLine(); s != null; s = reader.readLine()) {
				builder.append(s);
			}

			String jsonString = new String(builder.toString());

			if ("{}".equals(jsonString)) {
				return null;
			}

			return new JSONObject(jsonString);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static JSONObject getJSONArrayByPost(String uri, Map<String, String> data) {
		HttpParams httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, 8 * 1000);
		HttpConnectionParams.setSoTimeout(httpParams, 10 * 1000);
		HttpPost request = new HttpPost(uri);
		try {
			if (data != null) {
				// 注入参数
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				Set<String> keys = data.keySet();
				for (String key : keys) {
					params.add(new BasicNameValuePair(key, data.get(key)));
				}
				// 设置字符集
				HttpEntity httpentity = new UrlEncodedFormEntity(params, "utf8");
				// 请求httpRequest
				request.setEntity(httpentity);
			}
			// 取得默认的HttpClient
			HttpClient httpclient = new DefaultHttpClient(httpParams);
			// 取得HttpResponse
			HttpResponse httpResponse = httpclient.execute(request);
			// HttpStatus.SC_OK表示连接成功
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				// 取得返回的字符串
				String result = EntityUtils.toString(httpResponse.getEntity(), "utf8");
				return new JSONObject(result);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 使用post的方式，提交表单，不包括文件上传(老服务器写的代码使用这种方式)
	 * 
	 * @param actionUrl
	 * @param params
	 * @param files
	 * @return
	 * @throws IOException
	 */
	public static JSONObject postParams(String actionUrl, String query) {
		try {
			URL uri = new URL(actionUrl);
			HttpURLConnection conn = (HttpURLConnection) uri.openConnection();

			conn.setReadTimeout(10 * 1000);
			conn.setDoInput(true);// 允许输入
			conn.setDoOutput(true);// 允许输出
			conn.setUseCaches(false);
			conn.setRequestMethod("POST"); // Post方式
			conn.setRequestProperty("connection", "keep-alive");
			conn.setRequestProperty("Charsert", "UTF-8");

			// query is your body
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");// 请求头,
																							// 必须设置
			conn.setRequestProperty("Content-Length", query.toString().getBytes("UTF-8").length + "");// 注意是字节长度,
																										// 不是字符长度
			conn.getOutputStream().write(query.toString().getBytes("UTF-8"));
			// 得到响应码
			int res = conn.getResponseCode();

			if (res == HttpURLConnection.HTTP_OK) {
				StringBuffer stringBuffer = new StringBuffer();
				String readLine;
				BufferedReader responseReader;
				// 处理响应流，必须与服务器响应流输出的编码一致
				responseReader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
				while ((readLine = responseReader.readLine()) != null) {
					stringBuffer.append(readLine).append("/n");
				}
				responseReader.close();

				return new JSONObject(stringBuffer.toString());
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	public static void downloadFile(Context context, String url, Handler mHandler) {
		Log.d("Helpers", "begin to download file");
		String dstPath = "";
		String sdState=Environment.getExternalStorageState();
		   if(!sdState.equals(Environment.MEDIA_MOUNTED)){
			   File dir = context.getDir("files", Context.MODE_PRIVATE);
			   dstPath = dir.getAbsolutePath();
		   }else
		   {
			   dstPath = FileDirProvider.icon;
		   }
		Message message = new Message();
		String fileName = url.substring(url.lastIndexOf("=") + 1, url.length()) + ".png";
		String type = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
		File f = new File(dstPath, fileName);
		if (!f.exists()) {
			try {
				URL uri = new URL(url);
				HttpURLConnection urlConn = (HttpURLConnection) uri.openConnection();
				InputStream in = urlConn.getInputStream();
				if (!f.exists() && in != null) {
					File dest = new File(f.getPath());
					Helpers.createNewFile(dest);
					OutputStream out = new FileOutputStream(dest);
					byte[] buf = new byte[1024];
					int i = 0;
					while ((i = in.read(buf)) > 0) {
						out.write(buf, 0, i);
					}
					// out.flush();
					if (in != null) {
						in.close();
					}
					if (out != null) {
						out.close();
					}
				}
				if (in != null) {
					in.close();
				}
				urlConn.disconnect();
				// 校验文件是否已写成功，写失败则直接返回null
				if (!f.exists()) {
					message.what = MsgID.HEAD_DOWNLOAD_FAIL;
					mHandler.sendMessage(message);
				}
			} catch (Exception e) {
				e.printStackTrace();
				message.what = MsgID.HEAD_DOWNLOAD_FAIL;
				mHandler.sendMessage(message);
				return;
			}
			message.what = MsgID.HEAD_DOWNLOAD_SUCCESS;
			message.obj = f.getAbsolutePath();
			mHandler.sendMessage(message);
			return;
		}
		message.what = MsgID.HEAD_DOWNLOAD_SUCCESS;
		message.obj = f.getAbsolutePath();
		mHandler.sendMessage(message);
	}

	/**
	 * 根据路径获取Drawable
	 * 
	 * @param path
	 * @return
	 */
	public static Drawable getDrawableBySDPath(String path) {
		// SoftReference<Bitmap> bitmap = null;
		// try {
		File file = new File(path);
		if (file.exists()) {
			// 校验文件完整性
			BitmapFactory.Options opts = new BitmapFactory.Options();
			// // opts.inTempStorage = new byte[16 * 1024];
			//
			// opts.inSampleSize = 2;// 1/2
			// InputStream fIn = new FileInputStream(file);
			// bitmap = new SoftReference<Bitmap>(BitmapFactory.decodeStream(
			// fIn, null, opts));
			// if (fIn != null) {
			// fIn.close();
			// }
			opts.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(path, opts);

			opts.inSampleSize = computeSampleSize(opts, -1, 128 * 128);
			opts.inJustDecodeBounds = false;
			try {
				Bitmap bmp = BitmapFactory.decodeFile(path, opts);
				if (bmp != null) {
					SoftReference<Bitmap> softBitmap = new SoftReference<Bitmap>(bmp);
					return new BitmapDrawable(softBitmap.get());
					// return new BitmapDrawable(bmp);
				}
			} catch (OutOfMemoryError err) {
				err.printStackTrace();
			}
		}
		// } catch (FileNotFoundException e) {
		// e.printStackTrace();
		// } catch (IOException e) {
		// e.printStackTrace();
		// }

		// if (bitmap != null) {
		// return new BitmapDrawable(bitmap.get());
		// }
		return null;

	}

	public static int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
		int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);

		int roundedSize;
		if (initialSize <= 8) {
			roundedSize = 1;
			while (roundedSize < initialSize) {
				roundedSize <<= 1;
			}
		} else {
			roundedSize = (initialSize + 7) / 8 * 8;
		}

		return roundedSize;
	}

	private static int computeInitialSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
		double w = options.outWidth;
		double h = options.outHeight;

		int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
		int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(Math.floor(w / minSideLength),
				Math.floor(h / minSideLength));

		if (upperBound < lowerBound) {
			// return the larger one when there is no overlapping zone.
			return lowerBound;
		}

		if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
			return 1;
		} else if (minSideLength == -1) {
			return lowerBound;
		} else {
			return upperBound;
		}
	}

	/**
	 * 功能：show soft keyboard 创建人：huangbo 创建时间：2012-11-7
	 * 
	 * @param activity
	 */
	public static void showSoftKeyboard(Activity activity, View view) {
		((InputMethodManager) activity.getSystemService(activity.INPUT_METHOD_SERVICE)).showSoftInput(view, 0);
	}

	/**
	 * 功能：hide soft keyboard 创建人：huangbo 创建时间：2012-11-7
	 * 
	 * @param activity
	 */
	public static void hideSoftKeyboard(Activity activity) {
		if (activity == null) {
			return;
		}
		try {
			View focus = activity.getCurrentFocus();
			if (focus == null) {
				return;
			}
			InputMethodManager imm = ((InputMethodManager) activity.getSystemService(activity.INPUT_METHOD_SERVICE));
			imm.hideSoftInputFromWindow(focus.getWindowToken(), 0);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void showToast(Activity activity, String msg, int duration) {
		Toast toast = Toast.makeText(activity, msg, duration);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.show();
	}

	public static void showToast(Activity activity, int resId, int duration) {
		Toast toast = Toast.makeText(activity, resId, duration);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.show();
	}
	
	/**
     * 获取当前版本号
     */
    public static String getVersionName(Context context) {
        String versionName = null;
        try {
            versionName = context.getPackageManager().getPackageInfo("com.njrsrc", 0).versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }
}